<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Snap Context</title>
    <script src="marked.js"></script>
    <script src="js-base64.js"></script>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="katex.min.css">
    <script src="katex.min.js"></script>
</head>
<body>
<div id="content">
    Loading...
</div>
<script>
    const b64content = `##CONTENT_HERE##`
    const fontSize = parseInt(`##FONT_SIZE_HERE##`) + 3
    const fontFamily = `##FONT_FAMILY_HERE##`
    let content = Base64.decode(b64content).trim()
    content = content.replace(/\n+/g, '\n\n')
    content = content.replace(/\|\n\n\|/g, '|\n|')
    content = content.replace(/^\[(.*?)]\(#(.*?)\)/gm, '---\n\n### \\[$1\\]\\(#$2\\)')
    if (content.startsWith('---\n\n')) {
        content = content.substring(5)
    }
    let contentElem = document.getElementById('content');
    contentElem.innerHTML = renderMD(content)
    contentElem.setAttribute('style', 'font-family: "' + fontFamily + '";font-size: ' + fontSize + 'px;')
    window.scrollTo(0, document.body.scrollHeight)

    const copyButtonLabel = "Copy Code"
    let blocks = document.querySelectorAll("pre")
    blocks.forEach((block) => {
        if (navigator.clipboard) {
            let button = document.createElement("button");
            button.innerText = copyButtonLabel
            block.appendChild(button)
            button.addEventListener("click", async () => {
                await copyCode(block, button);
            })
        }
    })

    async function copyCode(block, button) {
        let text = block.querySelector("code").innerText
        fallbackCopyTextToClipboard(text)
        button.innerText = "Code Copied"
        setTimeout(() => {
            button.innerText = copyButtonLabel;
        }, 700)
    }

    function fallbackCopyTextToClipboard(text) {
        let textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.top = "0";
        textArea.style.left = "0";
        textArea.style.position = "fixed";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
            let successful = document.execCommand('copy');
            let msg = successful ? 'successful' : 'unsuccessful';
            console.log('Fallback: Copying text command was ' + msg);
        } catch (err) {
            console.error('Fallback: Oops, unable to copy', err);
        }
        document.body.removeChild(textArea);
    }

    function renderMD(content) {
        const renderer = new marked.Renderer()
        let i = 0
        const next_id = () => `__special_katext_id_${i++}__`
        const math_expressions = {}

        function replace_math_with_ids(text) {
            text = text.replace(/\$\$([\s\S]+?)\$\$/g, (_match, expression) => {
                const id = next_id()
                math_expressions[id] = {type: 'block', expression}
                return id
            })
            text = text.replace(/\$([^\n\s]+?)\$/g, (_match, expression) => {
                const id = next_id()
                math_expressions[id] = {type: 'inline', expression}
                return id
            })
            return text
        }

        const original_listitem = renderer.listitem
        renderer.listitem = function (text, task, checked) {
            return original_listitem(replace_math_with_ids(text), task, checked)
        }
        const original_paragraph = renderer.paragraph
        renderer.paragraph = function (text) {
            return original_paragraph(replace_math_with_ids(text))
        }
        const original_tablecell = renderer.tablecell
        renderer.tablecell = function (content, flags) {
            return original_tablecell(replace_math_with_ids(content), flags)
        }
        const original_text = renderer.text
        renderer.text = function (text) {
            return original_text(replace_math_with_ids(text))
        }
        const rendered_md_only = marked.parse(content, {renderer: renderer, mangle: false, headerIds: false})
        try {
            return rendered_md_only.replace(/(__special_katext_id_\d+__)/g, (_match, capture) => {
                const {type, expression} = math_expressions[capture]
                return katex.renderToString(expression, {displayMode: type === 'block'})
            })
        } catch (e) {
            console.log(e)
        }
        return rendered_md_only
    }
</script>
</body>
</html>